package com.sw.c.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 消息生产者工具类
 */
@Slf4j
@Service
public class RocketMQProducerUtil {
    @Resource
    private RocketMQTemplate rocketMQTemplate;


    /**
     *  同步发送消息
     * @param topic 主题
     * @param message 消息
     */
    public void sendSyncMessage(String topic, String message){
        try {
            rocketMQTemplate.syncSend(topic, MessageBuilder.withPayload(message).build());
            log.info("\n同步发送成功:\n主题：{}，\n消息：{}",topic, message);
        } catch (Exception e) {
            log.error("\n同步发送失败:\n主题：{}\n消息：{},异常信息：\n{}", topic, MessageBuilder.withPayload(message).build(),e.getMessage());
        }

    }

    /**
     *  异步发送消息
     * @param topic 主题
     * @param message 消息
     */
    public void sendAsyncMessage(String topic, String message){
        rocketMQTemplate.asyncSend(topic, MessageBuilder.withPayload(message).build(), new SendCallback() {

            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("异步发送成功:{}",sendResult);

            }

            @Override
            public void onException(Throwable throwable) {
                log.info("异步发送失败:{}",throwable.getMessage());
            }
        });
    }

    /**
     *   单向发送消息
     * @param topic 主题
     * @param message 消息
     */
    public void sendOneWayMessage(String topic, String message){
        try {
            rocketMQTemplate.sendOneWay(topic, MessageBuilder.withPayload(message).build());
            log.info("\n单向发送成功:\n主题：{}\n消息：{}",topic, message);
        } catch (Exception e) {
            log.error("\n单向发送失败:\n主题：{}\n消息：{},异常信息：\n{}", topic, MessageBuilder.withPayload(message).build(),e.getMessage());
        }
    }
}
